/*
 * @Author: xiaosihan
 * @Date: 2024-08-01 15:30:19
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-11-06 23:54:51
 */

import { Sequelize, DataTypes } from 'sequelize';
// 数据库对象
class Database {

    constructor() {
    }

    // 创建一个数据操作对象
    // 中文文档 https://github.com/demopark/sequelize-docs-Zh-CN/tree/v6
    sequelize = new Sequelize(
        process.env.DB_NAME?.trim() || '',
        process.env.DB_USER?.trim() || '',
        process.env.DB_PASSWORD?.trim() || '',
        {
            host: process.env.DB_HOST?.trim() || '',
            dialect: 'mysql',
            port: parseInt(process.env.DB_PORT?.trim() || '3306'),
            logging: false // 禁用SQL语句打印
        }
    );

    // 测试数据库连接
    async testConnection() {
        try {
            await this.sequelize.authenticate();
            console.log('✅ 数据库连接成功');
            return true;
        } catch (error) {
            console.error('❌ 数据库连接失败:', error);
            console.error('连接配置信息:');
            console.error(`  - 主机: ${process.env.DB_HOST || '未设置'}`);
            console.error(`  - 端口: ${process.env.DB_PORT || '3306'}`);
            console.error(`  - 数据库名: ${process.env.DB_NAME || '未设置'}`);
            console.error(`  - 用户名: ${process.env.DB_USER || '未设置'}`);
            return false;
        }
    }

    //创建一个用户表对象
    user = this.sequelize.define('user', {
        user_id: {
            autoIncrement: true,
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true
        },
        name: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        openid: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        avatar: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        sex: {
            type: DataTypes.INTEGER,
            allowNull: false,
        },
        phone: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        token: {
            type: DataTypes.STRING,
            allowNull: false,
        }
    }, {
        tableName: "user",
        timestamps: false,
        indexes: [
            {
                name: 'idx_token',
                fields: ['token']
            },
            {
                name: 'idx_openid',
                fields: ['openid']
            }
        ]
    });

    // 创建一张oss文件表
    oss_file = this.sequelize.define<any>('oss_file', {
        file_id: {
            autoIncrement: true,
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true
        },
        url: {
            type: DataTypes.TEXT('long'),
            allowNull: false
        },
        suffix: {
            type: DataTypes.STRING,
            allowNull: true,
        },
        optimized: {
            type: DataTypes.BOOLEAN,
            allowNull: false,
            defaultValue: false
        },
        used: {
            type: DataTypes.ENUM('unknown', 'nouse', 'used'),
            allowNull: false,
            defaultValue: 'unknown'
        }
    }, {
        tableName: "oss_file",
        timestamps: false,
        indexes: [
            {
                name: 'idx_optimized',
                fields: ['optimized']
            },
            {
                name: 'idx_used',
                fields: ['used']
            },
            {
                name: 'idx_suffix',
                fields: ['suffix']
            }
        ]
    });

    // 创建一张design表
    design = this.sequelize.define<any>('design', {
        id: {
            autoIncrement: true,
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true
        },
        data: {
            type: DataTypes.TEXT('long'),
            allowNull: false
        },
        order: {
            type: DataTypes.DECIMAL(10, 1),
            allowNull: true,
            defaultValue: 0.0
        }
    }, {
        tableName: "design",
        timestamps: false
    });

    // 创建一张myImg表
    myImg = this.sequelize.define<any>('myImg', {
        id: {
            autoIncrement: true,
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true
        },
        url: {
            type: DataTypes.TEXT('long'),
            allowNull: false
        },
        name: {
            type: DataTypes.STRING,
            allowNull: false
        },
        description: {
            type: DataTypes.STRING,
            allowNull: true
        },
        size: {
            type: DataTypes.INTEGER,
            allowNull: false
        },
        order: {
            type: DataTypes.DECIMAL(10, 1),
            allowNull: true,
            defaultValue: 0.0
        },
        createdAt: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW
        },
        updatedAt: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW
        }
    }, {
        tableName: "myImg",
        timestamps: true
    });

    // 创建一张cad_conversion表，用于存储DWG转换记录
    cadConversion = this.sequelize.define<any>('cadConversion', {
        id: {
            autoIncrement: true,
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true
        },
        originalFileName: {
            type: DataTypes.STRING,
            allowNull: false
        },
        originalFileUrl: {
            type: DataTypes.TEXT('long'),
            allowNull: false
        },
        originalFileSize: {
            type: DataTypes.INTEGER,
            allowNull: false
        },
        targetFormat: {
            type: DataTypes.ENUM('fbx', 'glb'),
            allowNull: false,
            defaultValue: 'glb'
        },
        convertedFileName: {
            type: DataTypes.STRING,
            allowNull: true
        },
        convertedFileUrl: {
            type: DataTypes.TEXT('long'),
            allowNull: true
        },
        status: {
            type: DataTypes.ENUM('pending', 'processing', 'completed', 'failed'),
            allowNull: false,
            defaultValue: 'pending'
        },
        errorMessage: {
            type: DataTypes.TEXT('long'),
            allowNull: true
        },
        progress: {
            type: DataTypes.INTEGER,
            allowNull: false,
            defaultValue: 0
        },
        createdAt: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW
        },
        updatedAt: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW
        }
    }, {
        tableName: "cad_conversion",
        timestamps: true
    });

    // 创建一张adminUser表
    adminUser = this.sequelize.define('adminUser', {
        admin_id: {
            autoIncrement: true,
            type: DataTypes.INTEGER,
            allowNull: false,
            primaryKey: true
        },
        username: {
            type: DataTypes.STRING,
            allowNull: false
        },
        password: {
            type: DataTypes.STRING,
            allowNull: false
        },
        admin_token: {
            type: DataTypes.STRING,
            allowNull: false
        },
        createdAt: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW
        },
        updatedAt: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: DataTypes.NOW
        }
    }, {
        tableName: "adminUser",
        timestamps: true,
        indexes: [
            {
                name: 'idx_admin_token',
                fields: ['admin_token']
            }
        ]
    });


}


const database = new Database();

// 初始化数据库连接并同步
async function initializeDatabase() {
    console.log('🔄 正在初始化数据库连接...');

    // 测试数据库连接
    const isConnected = await database.testConnection();

    if (isConnected) {
        // 连接成功，同步数据库结构
        try {
            await database.sequelize.sync({
                alter: true, // 同步字段,可以添加和删除字段 但是不会删表,也不会删 表和 索引
                logging: false
            });
            console.log('✅ 数据库结构同步完成');
        } catch (error) {
            console.error('❌ 数据库结构同步失败:', error);
        }
    } else {
        console.error('❌ 由于数据库连接失败，跳过数据库结构同步');
        console.error('请检查以下配置:');
        console.error('1. 环境变量是否正确设置 (.env 文件)');
        console.error('2. MySQL服务是否正在运行');
        console.error('3. 数据库连接参数是否正确');
        console.error('4. 网络连接是否正常');
    }
}

// 执行数据库初始化
initializeDatabase();

export default database;
